package com.cyzy.utils;

import java.io.*;
import java.net.*;

public class SoilDetectionUtil {

    private static final String DEFAULT_HOST = "tcp://g8a2d4c2.natappfree.cc:35396";
    private static final int DEFAULT_PORT = 8083;

    /**
     * 发送土壤检测请求并接收响应
     * @param host 服务器地址
     * @param port 服务器端口
     * @param request 请求内容
     * @return 服务器响应
     */
    public static String sendDetectionRequest(String host, int port, String request) {
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println(request); // 发送请求
            System.out.println("已发送请求: " + request);

            String response = in.readLine(); // 接收响应
            System.out.println("收到服务端数据: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用默认服务器地址和端口发送土壤检测请求
     * @param request 请求内容
     * @return 服务器响应
     */
    public static String sendDetectionRequest(String request) {
        return sendDetectionRequest(DEFAULT_HOST, DEFAULT_PORT, request);
    }

    public static void main(String[] args) {
        // 测试土壤检测工具类
        String request = "1"; // 示例请求内容
        String response = SoilDetectionUtil.sendDetectionRequest("g8a2d4c2.natappfree.cc",35396,request);
        if (response != null) {
            System.out.println("土壤检测结果: " + response);
        }
    }
}
